<template>
  <div class="arrangework">
    <div class="top">
      <div class="tip">员工周排班表</div>
      <div style="margin-left:30px;margin-right:15px;">设置休息日</div>
      <el-select
        v-model="restDay"
        placeholder="请选择"
        :disabled="isDisabledRestDay"
      >
        <el-option
          v-for="(item, index) in weekOptions"
          :key="index"
          :label="item.value"
          :value="item.key"
        ></el-option>
      </el-select>
      <!-- <div style="margin-left:100px;margin-right:10px;">设置请假时间</div>
      <el-date-picker
        v-model="startTime"
        type="datetime"
        placeholder="选择开始时间"
        size="small"
        value-format="yyyy-MM-dd HH:mm"
        format="yyyy-MM-dd HH:mm"
        :clearable="isclear"
        :picker-options="pickerOptionsStart"
        :disabled="isdisableStart"
        popper-class="startwork"
      >
      </el-date-picker> -->
      <!-- <span style="margin:0 5px;">至</span>
      <el-date-picker
        v-model="endTime"
        type="datetime"
        placeholder="选择结束时间"
        size="small"
        value-format="yyyy-MM-dd HH:mm"
        format="yyyy-MM-dd HH:mm"
        :clearable="isclear"
        :picker-options="pickerOptionsEnd"
        @change="val => changeEndTime(val, this.endTime)"
        popper-class="endwork"
      >
      </el-date-picker> -->
      <el-button
        v-if="this.$route.query.staffCode"
        style="background-color:#fd804c;color: #fff;padding:7px 10px;margin-left:50px;"
        @click="goToStaffUse"
        >员工资源占用</el-button
      >
    </div>
    <div class="bottom" v-if="this.$route.query.staffCode">
      <div class="header">
        <div class="headleft" style="display:flex;">
          <div style="cursor:pointer;" @click="weekPrev">
            <i class="el-icon-arrow-left"></i>
          </div>
          <div class="weekdate">{{ `${weekstartTime} 至 ${weekendTime}` }}</div>
          <div style="cursor:pointer;" @click="weekNext">
            <i class="el-icon-arrow-right"></i>
          </div>
          <div>
            <span
              style="margin-left:8px;color:#1989fa;text-decoration:underline;cursor:pointer;"
              @click="gotoNow"
              >回到本周</span
            >
          </div>
        </div>
        <div class="headright" style="display:flex;">
          <div class="iconbox3"></div>
          <div style="margin-left:5px;">不可约</div>
          <div class="iconbox2">
            <i class="el-icon-check"></i>
          </div>
          <div style="margin-left:5px;">已满</div>
          <div class="iconbox">
            <i class="el-icon-check"></i>
          </div>
          <div style="margin-left:5px;">可约</div>
        </div>
      </div>
      <el-table :data="tableData" border stripe style="width:100%;">
        <el-table-column prop="week" label="日期/时间" width="60">
          <template slot-scope="scope">
            {{
              weekOptions[scope.row.week]
                ? weekOptions[scope.row.week].value
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in tableData[0].staffSchedulingTimeVoList"
          :key="index"
          :label="item.timeSlot"
          width="40"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <!-- {{scope.row.statusList[index].status}} -->
            <!-- 可约 -->
            <div
              class="iconbox"
              v-if="
                scope.row.staffSchedulingTimeVoList[index].timeSubStatus == 4
              "
            >
              <i class="el-icon-check"></i>
            </div>
            <!-- 已约满 -->
            <div
              class="iconbox2"
              v-if="
                scope.row.staffSchedulingTimeVoList[index].timeSubStatus == 1
              "
            >
              <i class="el-icon-check"></i>
            </div>
            <!-- 不可约（包含请假和休息日） -->
            <div
              class="iconbox3"
              style="margin-left:13px;"
              v-if="
                scope.row.staffSchedulingTimeVoList[index].timeSubStatus == 2 ||
                  scope.row.staffSchedulingTimeVoList[index].timeSubStatus == 3
              "
            ></div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import moment from "moment";
const weekOptions = [
  {
    key: "0",
    value: "星期日"
  },
  {
    key: "1",
    value: "星期一"
  },
  {
    key: "2",
    value: "星期二"
  },
  {
    key: "3",
    value: "星期三"
  },
  {
    key: "4",
    value: "星期四"
  },
  {
    key: "5",
    value: "星期五"
  },
  {
    key: "6",
    value: "星期六"
  },
  {
    key: "",
    value: "未选择"
  }
];
export default {
  props: {
    staffBasicVo1: {
      required: false
    }
  },
  computed: {
    pickerOptionsStart() {
      return {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      };
    },
    pickerOptionsEnd() {
      const _this = this;
      return {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      };
    },
    isDisabledRestDay() {
      const staffCode = this.$route.query.staffCode || "";
      if (!staffCode) {
        // 新增
        return false;
      } else {
        // 编辑
        return false;
      }
    }
  },
  data() {
    return {
      restDay: "",
      startTime: "",
      endTime: "",
      weekstartTime: "",
      weekendTime: "",
      weekOptions,
      tableData: [
        {
          week: "",
          staffSchedulingTimeVoList: []
        }
      ],
      isclear: true,
      isdisableStart: false,
      isTimeMsgFromBack: false, // 请假时间是否来自后端
      prevEndTime: "" // 接口返回的请假结束时间
    };
  },
  methods: {
    changeTrStyle({ row, column, rowIndex, columnIndex }) {
      let progressRate = row.colorList;
      if (columnIndex > 0) {
        const currentIndex = columnIndex - 1;
        switch (progressRate[currentIndex].status) {
          case 1:
            return "developing";
            break;
          case 2:
            return "testing";
            break;
          case 3:
            return "publishing";
            break;
        }
      }
    },
    getCurrentWeekTime() {
      // 获取当前本周的开始时间和结束时间
      let data = new Date(); //当前日期
      let year = Number(data.getFullYear()); //当前年
      let month = Number(data.getMonth()) + 1;
      let nowMonth = Number(data.getMonth()); //当前月
      let day = Number(data.getDate()); //当天
      //计算某日是本月第几周
      let mydate = new Date(year, month - 1, day);
      let weekday = mydate.getDay(); //获取该日是星期几，0代表星期日//今天本周的第几天
      let weekno = Math.ceil((day + 6 - weekday) / 7); // 本月第几周
      //console.log("本月第几周:" + weekno);
      //获取当前周的开始结束时间
      let startTime; //本周的开始时间
      let endTime; //本周的结束时间
      function formatDate(date) {
        let myyear = Number(date.getFullYear());
        let mymonth = Number(date.getMonth() + 1);
        let myweekday = Number(date.getDate());
        if (mymonth < 10) {
          mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
          myweekday = "0" + myweekday;
        }
        return myyear + "-" + mymonth + "-" + myweekday;
      }

      //获得本周的开始日期
      function getWeekStartDate() {
        let weekStartDate = new Date(year, nowMonth, day + 1 - weekday);
        return formatDate(weekStartDate);
      }

      //获得本周的结束日期
      function getWeekEndDate() {
        let weekEndDate = new Date(year, nowMonth, day + 7 - weekday);
        return formatDate(weekEndDate);
      }

      startTime = getWeekStartDate();
      endTime = getWeekEndDate();
      this.weekstartTime = startTime;
      this.weekendTime = endTime;
    },
    async weekPrev() {
      // 上一周
      const weekstartTime = moment(this.weekstartTime)
        .subtract("7", "days")
        .format("YYYY-MM-DD");
      const weekendTime = moment(this.weekendTime)
        .subtract("7", "days")
        .format("YYYY-MM-DD");
      await this.$http({
        url: "/staffadmin/homeService/staffManager/fetchStaffSchedulingList",
        method: "get",
        params: {
          startTime: weekstartTime,
          endTime: weekendTime,
          staffCode: this.$route.query.staffCode
            ? this.$route.query.staffCode
            : ""
        }
      }).then(data => {
        if (data.length == 0) {
          this.$message.error("暂无排班");
        }
        if (data.length > 0) {
          this.weekstartTime = weekstartTime;
          this.weekendTime = weekendTime;
          if (data.length == 7) {
            this.tableData = data;
          }
          if (data.length < 7) {
            this.tableData = data;
            this.addData();
          }
        }
      });
    },
    async weekNext() {
      // 下一周
      const weekstartTime = moment(this.weekstartTime)
        .add("7", "days")
        .format("YYYY-MM-DD");
      const weekendTime = moment(this.weekendTime)
        .add("7", "days")
        .format("YYYY-MM-DD");
      await this.$http({
        url: "/staffadmin/homeService/staffManager/fetchStaffSchedulingList",
        method: "get",
        params: {
          startTime: weekstartTime,
          endTime: weekendTime,
          staffCode: this.$route.query.staffCode
            ? this.$route.query.staffCode
            : ""
        }
      }).then(data => {
        if (data.length == 0) {
          this.$message.error("暂无排班");
        }
        if (data.length > 0) {
          this.weekstartTime = weekstartTime;
          this.weekendTime = weekendTime;
          if (data.length == 7) {
            this.tableData = data;
          }
          if (data.length < 7) {
            this.tableData = data;
            this.addData();
          }
        }
      });
      // this.weekstartTime =
      // this.weekendTime =
    },
    gotoNow() {
      // 回到本周
      this.getCurrentWeekTime();
      this.fetchStaffSchedulingList();
    },
    sendMsg() {
      this.$emit("save", {
        leaveStartTime: this.startTime
          ? moment(this.startTime).format("YYYY-MM-DD HH:mm:ss")
          : this.startTime,
        leaveEndTime: this.endTime
          ? moment(this.endTime).format("YYYY-MM-DD HH:mm:ss")
          : this.endTime,
        restDay: this.restDay,
        staffCode: this.$route.query.staffCode
          ? this.$route.query.staffCode
          : ""
      });
      //console.log(moment(this.startTime).format("YYYY-MM-DD HH:mm:ss"));
      //console.log(moment(this.endTime).format("YYYY-MM-DD HH:mm:ss"));
    },
    async fetchStaffSchedulingList() {
      // 获取排班信息
      await this.$http({
        url: "/staffadmin/homeService/staffManager/fetchStaffSchedulingList",
        method: "get",
        params: {
          startTime: this.weekstartTime,
          endTime: this.weekendTime,
          staffCode: this.$route.query.staffCode
            ? this.$route.query.staffCode
            : ""
        }
      }).then(data => {
        if (data.length > 0) {
          this.tableData = data;
          // 前端手动补充数据
          if (data.length < 7) {
            this.addData();
          }
        }
      });
    },
    addData() {
      // tableData中的礼拜几开始   礼拜几结束  前端自动补充整个礼拜  前后都补
      const startIndex = Number(this.tableData[0].week);
      const endIndex = Number(
        this.tableData[Number(this.tableData.length) - 1].week
      );
      const copyTableData = JSON.parse(JSON.stringify(this.tableData));
      const buKeYuestaffSchedulingTimeVoList = copyTableData[0].staffSchedulingTimeVoList.map(
        item => {
          return {
            timeSlot: item.timeSlot,
            timeSubStatus: "2"
          };
        }
      );
      const KeYuestaffSchedulingTimeVoList = copyTableData[0].staffSchedulingTimeVoList.map(
        item => {
          return {
            timeSlot: item.timeSlot,
            timeSubStatus: "4"
          };
        }
      );
      if (startIndex != 1) {
        // 头部缺数据  补头部数据
        for (let i = startIndex - 1; i > 0; i--) {
          copyTableData.unshift({
            week: i + "",
            staffSchedulingTimeVoList: buKeYuestaffSchedulingTimeVoList
          });
        }
        this.tableData = copyTableData;
      }
      if (startIndex == 1) {
        // 尾部缺数据 补尾部数据(补成可约，休息日除外)
        for (let j = 0; j < 7 - endIndex; j++) {
          copyTableData.push({
            week: endIndex + j + 1 + "",
            staffSchedulingTimeVoList: KeYuestaffSchedulingTimeVoList
          });
        }
        copyTableData[Number(copyTableData.length - 1)].week = "0"; // 最后一条
        // 判断后端返回的的天数是否含有休息日(不去判断休息日在后端返回的数据中  还是在前端后补的数据中 整体直接修改)
        const restDay = this.restDay;
        if (restDay == "") {
          this.tableData = copyTableData;
          return false;
        }
        const restDayIndex = copyTableData.findIndex(item => {
          return item.week == restDay;
        });
        copyTableData[
          restDayIndex
        ].staffSchedulingTimeVoList = buKeYuestaffSchedulingTimeVoList;
        this.tableData = copyTableData;
      }
    },
    // 初始化页面
    initData() {
      if (this.staffBasicVo1.restDay) {
        this.restDay = this.staffBasicVo1.restDay;
      }
      if (
        this.staffBasicVo1.staffSchedulingHistory &&
        this.staffBasicVo1.staffSchedulingHistory.evalStartTime &&
        this.staffBasicVo1.staffSchedulingHistory.evalEndTime
      ) {
        this.startTime = this.staffBasicVo1.staffSchedulingHistory.evalStartTime;
        this.endTime = this.staffBasicVo1.staffSchedulingHistory.evalEndTime;
        this.isclear = false;
        this.isdisableStart = true;
        this.isTimeMsgFromBack = true;
        this.prevEndTime = this.staffBasicVo1.staffSchedulingHistory.evalEndTime;
      }
    },
    changeEndTime(newvalue, oldvalue) {
      // 修改请假结束时间
      if (this.isTimeMsgFromBack) {
        // 结束时间来自后端   时间不能往后移
        const endTime = moment(this.endTime, "YYYY-MM-DD HH:mm");
        const prevEndTime = moment(this.prevEndTime, "YYYY-MM-DD HH:mm");
        const diff1 = moment(endTime).diff(moment(prevEndTime), "minutes");
        if (diff1 > 0) {
          this.$message.error("请假结束时间只能往前，不能往后移动");
          this.endTime = this.prevEndTime; // 结束时间重置回去
        }
      }
    },
    goToStaffUse() {
      // 跳转员工资源占用页面
      this.$router.push({
        path: "/staffUse",
        query: {
          staffCode: this.$route.query.staffCode
        }
      });
    }
  },
  activated() {
    this.getCurrentWeekTime(); // 获取本周的初始日期和结束日期
    this.fetchStaffSchedulingList(); // 获取本周的排班信息
  },
  watch: {
    restDay: {
      handler(newvalue) {
        this.sendMsg();
      },
      deep: true,
      immediate: true
    },
    startTime: {
      handler(newvalue) {
        this.sendMsg();
      },
      deep: true,
      immediate: true
    },
    endTime: {
      handler(newvalue) {
        this.sendMsg();
      },
      deep: true,
      immediate: true
    },
    staffBasicVo1(newvalue) {
      if (newvalue && this.$route.query.staffCode) {
        this.initData();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.arrangework {
  background-color: #fff;
  border-top: 10px solid #ebeef1;
  border-bottom: 10px solid #ebeef1;
  /deep/ .top {
    padding-top: 20px;
    padding-bottom: 20px;
    display: flex;
    align-items: center;
    margin-left: 20px;
    font-size: 14px;
    .tip {
      font-size: 18px;
      font-weight: 900;
    }
    .el-select {
      .el-input__inner {
        height: 30px;
        width: 120px;
      }
      .el-input__icon {
        line-height: 30px;
      }
    }
    .el-date-editor {
      width: 170px;
    }
    .el-range-input {
      width: 130px;
    }
  }
  /deep/ .bottom {
    margin: 0 20px;
    margin-top: 20px;
    margin-bottom: 20px;
    .el-table {
      font-size: 12px;
      th {
        font-weight: 500;
      }
      .cell.el-tooltip {
        min-width: 40px;
      }
    }
    .cell {
      padding-left: 0;
      padding-right: 0;
    }
    .iconbox {
      width: 16px;
      height: 16px;
      border: 1px solid #ff7f4c;
      text-align: center;
      line-height: 15px;
      border-radius: 50%;
      color: #fff;
      background-color: #ff7f4c;
      box-sizing: border-box;
      margin-left: 13px;
      cursor: pointer;
    }
    .iconbox2 {
      width: 16px;
      height: 16px;
      border: 1px solid #cfcdcb;
      text-align: center;
      line-height: 15px;
      border-radius: 50%;
      color: #fff;
      background-color: #cfcdcb;
      box-sizing: border-box;
      margin-left: 13px;
      cursor: pointer;
    }
    .iconbox3 {
      width: 15px;
      height: 15px;
      box-sizing: border-box;
      border: 1px solid #cfcdcb;
      border-radius: 50%;
    }
    .header {
      width: 100%;
      height: 70px;
      border: 1px solid #ebeef5;
      border-bottom: none;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      padding: 0 30px;
    }
    .el-table tr td.developing {
      background: #ffe4b5;
      opacity: 0.9;
    }
    .el-table tr td.testing {
      background: #ffa500;
      opacity: 0.9;
    }
    .el-table tr td.publishing {
      background: #87cefa;
      opacity: 0.9;
    }
    .el-table tr td.published {
      background: #9acd32;
      opacity: 0.9;
    }
    .weekdate {
      margin: 0 6px;
    }
  }
}
</style>
